package com.rock.drawboard.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetworkUtil {

    private NetworkUtil() {
    }

    private static class SingleTonHolder{ private static NetworkUtil INSTANCE = new NetworkUtil();}

    public static NetworkUtil getInstance(){ return SingleTonHolder.INSTANCE;}

    public String getIPAddress(Context context) throws SocketException {
        String address = null;
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isConnected()){
            if(networkInfo.getType() == ConnectivityManager.TYPE_MOBILE){//2G,3G,4G
                address = getIPAddressForNetwork();
            }else if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI){//WIFI
                address = getIPAddressForWifi(context);
            }
        }
        return address;
    }


    public String getIPAddressForNetwork() throws SocketException {
        String address = null;
        for(Enumeration<NetworkInterface> enum1 = NetworkInterface.getNetworkInterfaces(); enum1.hasMoreElements();){
            NetworkInterface networkInterface = enum1.nextElement();
            for(Enumeration<InetAddress> enum2 = networkInterface.getInetAddresses(); enum2.hasMoreElements();){
                InetAddress inetAddress = enum2.nextElement();
                if(!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address){
                    address = "手机网络IP: " + inetAddress.getHostAddress().toString();
                }
            }
        }
        return address;
    }

    public String getIPAddressForWifi(Context context) {
        WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);

        if(!wifiManager.isWifiEnabled()){
            wifiManager.setWifiEnabled(true);
        }

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        String address = "type: WIFI\nIP地址: " + intIP2String(wifiInfo.getIpAddress()) + "\nMAC地址：" + wifiInfo.getMacAddress();
        String address = "WIFI-IP:" + intIP2String(wifiInfo.getIpAddress());
        return address;
    }

    public String intIP2String(int ip){
        return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 24) & 0xFF);
    }
}
